# -*- coding: utf-8 -*-
import xlrd
import logging
import sys
import re
import requests

reload(sys)
sys.setdefaultencoding('utf8')

logging.basicConfig(
    level=logging.WARN,
    format='%(asctime)s  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='login.log',
    filemode='a')

console = logging.StreamHandler()
console.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s  %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

header = {
    "Referer": "https://razerid.razer.com/",
    'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) Gecko/20100101 Firefox/60.0",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With": "XMLHttpRequest"
}

register = xlrd.open_workbook(r'register.xls')
sheet0 = register.sheet_by_index(0)
rows = sheet0.nrows


def register(email, id, password):
    success = '注册失败'

    session = requests.session()

    data = {
        "razerId": id
    }

    response = session.post("https://razerid.razer.com/ajax/check-razer-id", data=data, headers=header)
    result = response.text

    if result.__contains__('Success'):
        success = 'id验证通过'

        cookie = response.cookies.get_dict()
        response = session.get("https://razerid.razer.com/new", cookies=cookie)

        pattern_read = re.compile(ur"readToken: '(.*?)',")
        pattern_consent = re.compile(ur"consentToken: '(.*?)',")
        m = pattern_read.search(response.text)
        n = pattern_consent.search(response.text)
        if m:
            read = m.group(1)
            consent = n.group(1)

            read = str(read).replace('\\x2B', '+').replace('\\x2F', '/').replace('\\x3D', '=')
            consent = str(consent).replace('\\x2B', '+').replace('\\x2F', '/').replace('\\x3D', '=')

            data = {
                "email": email,
                "razerId": id,
                "password":	password,
                "serviceCode": "0060",
                "consentToken": consent,
                "readToken": read
            }

            response = requests.post("https://razerid.razer.com/ajax/user-create", data=data, headers=header)

            result = response.text

            print result

            if result.__contains__('Success'):
                success = '注册成功'

                data = {
                    "email": email,
                    "password":	password,
                    "body": '{"apps":[{"app_name":"rzrstore","check":0},{"app_name":"gamestore","check":0},{"app_name":"zvault","check":0},{"app_name":"cortex","check":0},{"app_name":"rzrpmk","check":0}]}'
                }

                response = session.post("https://razerid.razer.com/ajax/newsletter-internal-post", data=data, headers=header)

                result = response.text

                print result

                if result.__contains__('Success'):
                    success = '邮件发送成功'

    logging.warn('帐号 '+email+'   结果 '+success)


def main():
    try:
        for i in range(rows):
            register(sheet0.row_values(i)[0], sheet0.row_values(i)[1], sheet0.row_values(i)[2])
    except BaseException as e:
        print e.message
    finally:
        requests.session().close()


if __name__ == '__main__':
    main()
